package com.example.composeapp

import android.content.res.Configuration
import android.content.res.Resources
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.os.Parcel
import android.os.Parcelable
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.mapSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.*
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.res.ResourcesCompat
import com.example.composeapp.ui.theme.ComposeAppTheme
import kotlinx.android.parcel.Parcelize
import androidx.core.content.ContextCompat.startActivity

import android.content.Intent
import android.net.Uri
import android.provider.UserDictionary
import androidx.compose.foundation.*
import androidx.compose.foundation.text.ClickableText
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.text.selection.DisableSelection
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.drawscope.inset
import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.graphics.drawscope.withTransform
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.core.content.ContextCompat


class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ComposeAppTheme(false) {
                // A surface container using the 'background' color from the theme
                Surface(color = Color.Red) {
//                    Greeting(Message("Android", "nihaoya"))

//                    HelloScreen()

//                    CityScreen()

                    val list = mutableListOf<Message>()
                    repeat(1){
                        list.add(Message("a", "b"))
                        list.add(Message("sdfkjabkf", "四道口附近啊看覅五俄方\n第三方Jeri给你\n是的客房内日光拜访女方"))
                        list.add(Message("sdfkjabkf", "四道口附近啊看覅五俄方"))
                        list.add(Message("sdfkjabkf", "asdf\n第三方Jeri给你\n是的客房内日光拜访女方"))
                        list.add(Message("sdfkjabkf", "四道口附近啊看覅五俄方"))
                        list.add(Message("sdfkjabkf", "四道口附近啊看覅都是浪费你为方便上的覅华为氟化锇反纳粹上的覅无法五俄方"))
                    }
                    Conversation(list, resources)
                }
            }
        }
    }
}

data class Message (val author: String, val content: String)

@Composable
fun Greeting(message: Message, resources: Resources) {
    val context = LocalContext.current
    Row (modifier = Modifier
        .padding(bottom = 2.dp)
//        .height(60.dp)
        .fillMaxSize()
        .background(Color.Green)
        .clickable {
            Toast
                .makeText(context, "点击整个条目！", Toast.LENGTH_SHORT)
                .show()
        },
        horizontalArrangement = Arrangement.Start,
        verticalAlignment = Alignment.CenterVertically){
        Image(painter = painterResource(id = R.drawable.person),
            contentDescription = "md",
            modifier = Modifier
                .padding(start = 10.dp)
                .size(40.dp)
                .clip(CircleShape)
                .border(
                    1.5.dp,
                    MaterialTheme.colors.secondary,
                    CircleShape
                )
        )

        Spacer(modifier = Modifier.width(8.dp))
        Image(painter = painterResource(id = R.mipmap.error),
            contentDescription = "",
            modifier = Modifier
                .size(50.dp)
                .clip(CircleShape)
                .border(
                    1.5.dp,
                    MaterialTheme.colors.secondary,
                    CircleShape
                )
        )
        Spacer(modifier = Modifier.width(8.dp))
        Image(painter = painterResource(id = R.mipmap.error2),
            contentDescription = "",
            modifier = Modifier
                .size(50.dp)
                .clip(CircleShape)
                .border(
                    1.5.dp,
                    MaterialTheme.colors.secondary,
                    CircleShape
                )
                .clickable {
                    Toast
                        .makeText(context, "点击图片", Toast.LENGTH_SHORT)
                        .show()
                }
        )
        Spacer(modifier = Modifier.width(8.dp))
        Image(bitmap = ((ResourcesCompat.getDrawable(resources, R.mipmap.error,null))
                as BitmapDrawable).bitmap.asImageBitmap(),
            contentDescription = "图片",
            modifier = Modifier
                .size(40.dp)
                .clip(RoundedCornerShape(6.dp))
                .border(
                    1.5.dp,
                    MaterialTheme.colors.secondary,
                    RoundedCornerShape(6.dp)
                ),
            contentScale = ContentScale.Crop
        )
        Spacer(modifier = Modifier.width(8.dp))


        //We toggle the isExpanded variable when we click on this Column
        Column(modifier = Modifier
            .padding(top = 10.dp, bottom = 10.dp, end = 10.dp)
            .clickable {
                Toast
                    .makeText(context, "点击右侧文字", Toast.LENGTH_SHORT)
                    .show()
            }) {
            Text(text = "Hello ${message.author}!",
                color = MaterialTheme.colors.secondaryVariant,
                style = MaterialTheme.typography.subtitle2)

            Spacer(modifier = Modifier.height(5.dp))


            // We keep track if the message is expanded or not in this
            // variable
            var isExpanded by rememberSaveable { mutableStateOf(false) }
            // surfaceColor will be updated gradually from one color to the other
            val surfaceColor: Color by animateColorAsState(
                if (isExpanded) MaterialTheme.colors.primary else MaterialTheme.colors.surface,
            )

            Surface(shape = MaterialTheme.shapes.medium,
                elevation = 1.dp,
                // surfaceColor color will be changing gradually from primary to surface
                color = surfaceColor,
                // animateContentSize will change the Surface size gradually
                modifier = Modifier
                    .animateContentSize()
                    .padding(1.dp)
            ) {
                Text(text = message.content,
                    color = Color.Green,//文字颜色
//                    fontSize = 40.sp,//文字字体大小
                    fontStyle = FontStyle.Italic,//斜体
                    fontWeight = FontWeight.Bold,//文字加粗
                    modifier = Modifier
                        .padding(all = 4.dp)
                        .clickable {
                            isExpanded = !isExpanded
                            Toast
                                .makeText(
                                    context,
                                    if (isExpanded) "展开" else "关闭",
                                    Toast.LENGTH_SHORT
                                )
                                .show()
                        },
                    // If the message is expanded, we display all its content
                    // otherwise we only display the first line
                    maxLines = if (isExpanded) Int.MAX_VALUE else 1,
                    style = MaterialTheme.typography.body2)
            }

        }
    }
}

@Preview(showBackground = true,
    backgroundColor = 0xffffff,
        name = "Light Mode",
    showSystemUi = true)
//@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES,
//    showBackground = true,
//    name = "Dark Mode")
@Composable
fun DefaultPreview() {
    ComposeAppTheme {
        Greeting(Message("Android", "laban"), resources = Resources.getSystem())
    }
}

@Composable
fun Conversation(messages: List<Message>, resources: Resources) {
    val context = LocalContext.current
    LazyColumn {
        item {
            Box(
                modifier = Modifier
//                    .height(50.dp)
                    .fillMaxSize()
                    .padding(bottom = 2.dp)
                    .background(color = Color.Yellow),
                contentAlignment = Alignment.Center,
                propagateMinConstraints = false
            ) {

                Text(
                text = stringResource(id = R.string.app_name).repeat(1),
//                text = "这是头部".repeat(1),
                modifier = Modifier
////                    .height(50.dp)
                    .padding(5.dp)
                    .fillMaxSize()
////                    .gravity(Alignment.CenterVertically)
                    .background(Color.White),
                color = Color(R.color.teal_200),
                fontSize = 20.sp,
                fontStyle = FontStyle.Italic,//斜体
                fontWeight = FontWeight.Bold,//加粗
                textAlign = TextAlign.Center,//文本对齐方式，左对齐/右对齐/居中对齐/分散对齐/头对齐/尾对齐
                fontFamily = FontFamily.Serif,//字体
//                maxLines = 2,
                overflow = TextOverflow.Ellipsis,//尾部处理 文本超出显示方式，裁剪/省略号/显示
//                textDecoration = TextDecoration.Underline,
                onTextLayout = {  },//文本布局回调
//                letterSpacing = 1.sp,
//                lineHeight = 20.sp,
//                softWrap = true,//是否应在换行符处断开文本
                //样式，TextStyle可以自定义许多东西，除了以上大部分内容还有更多的东西，适合用来自定义更复杂的字体样式
                style = TextStyle.Default
            )
            }
        }

        items(messages, key = { it.author }) { message ->
            Greeting(message, resources)
        }

//        val firaSansFamily = FontFamily(//设置文字的组合样式
//            Font(R.font.firasans_light, FontWeight.Light),
//            Font(R.font.firasans_regular, FontWeight.Normal),
//            Font(R.font.firasans_italic, FontWeight.Normal, FontStyle.Italic),
//            Font(R.font.firasans_medium, FontWeight.Medium),
//            Font(R.font.firasans_bold, FontWeight.Bold)
//        )

        // 显示单个的UI，可以用作多个列表的分割，或者头部、底部之类的
        item {
            val textLink = buildAnnotatedString {
                withStyle(ParagraphStyle()) {//段落样式
                    append("我")
                    withStyle(SpanStyle(color = Color.Black)) {//跨度样式
                        append("的网站:")
                    }

                    // 我们将此 URL 注释附加到以下内容，直到调用 `pop()`
                    pushStringAnnotation(tag = "URL",annotation = "https://www.Baidu.com")
                    withStyle(SpanStyle(color = Color.Red, fontSize = 20.sp,
                        fontStyle = FontStyle.Normal, textDecoration = TextDecoration.Underline)) {
                        append("百度  百度")
                    }
                    pop()//超链接设置结束

                }
                withStyle(ParagraphStyle()) {//新起段落
                    withStyle(SpanStyle(color = Color.Blue)){
                        append("newLine")
                    }
                }
            }

                ClickableText(text = textLink,
                    Modifier
                        .fillMaxWidth()
                        .fillMaxHeight()
//                    .padding(1.dp)
                        .background(Color.Cyan),
                    onClick = {
                        // 我们检查点击位置的文本是否有 URL 注释
                        println("-------<$it")
                        textLink.getStringAnnotations(tag = "URL", start = it, end = it)
                            .firstOrNull()
                            ?.let { annotation ->
                                val url = annotation.item
                                //后面即逻辑操作...
                                val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                                context.startActivity(browserIntent)
                            }
                    },
                )


        }

        item {
            SelectionContainer {
                Column(modifier = Modifier
                    .fillMaxWidth()
                    .background(Color.Magenta)) {
                    Text("This text is selectable")
                    Text("This one too")
                    Text("This one as well")
                    DisableSelection {
                        Text("But not this one")
                        Text("Neither this one")
                    }
                    Text("But again, you can select this one")
                    Text("And this one too")
                }
            }
        }

        item{
            Surface(color = Color.White, modifier = Modifier.fillMaxWidth()) {
                HelloScreen()
            }
        }

        item {
            Canvas(modifier = Modifier.height(100.dp).fillMaxWidth().background(Color.Green)) {
                val canvasWidth = size.width
                val canvasHeight = size.height

                drawLine(
                    start = Offset(x = canvasWidth, y = 0f),
                    end = Offset(x = 0f, y = canvasHeight),
                    color = Color.Red,
                    strokeWidth = 5F
                )

                drawCircle(
                    color = Color.Blue,
                    center = Offset(x = canvasWidth / 2, y = canvasHeight / 2),
                    radius = size.minDimension / 4
                )

                drawRect(color = Color.Red,
                    topLeft = Offset(x = canvasWidth / 4, y = canvasHeight / 4),
                    size = size / 4F//Size(100f, 100f)
                )

                println("---->$canvasWidth    $canvasHeight")
                inset(canvasWidth * 2/4F, canvasHeight * 2/4F) {
                    rotate(degrees = -45F) {
                        drawRect(
                            color = Color.Magenta,
                            size = Size(canvasHeight / 2f,canvasHeight / 2f)
                        )
                    }
                }

                withTransform({//同时平移和旋转
                    translate(left = canvasWidth / 3F)
                    rotate(degrees = 45F)
                }) {
                    drawRect(
                        color = Color.Gray,
                        topLeft = Offset(x = canvasWidth / 3F, y = canvasHeight / 3F),
                        size = size / 3F
                    )
                }
            }
        }

    }
}

//@Preview
@Composable
fun PreviewConversation() {
    ComposeAppTheme() {
        Conversation(listOf(Message("a", "b"),
            Message("sdfkjabkf", "四道口附近啊看覅五俄方"),
            Message("sdfkjabkf", "四道口附近啊看覅五俄方"),
            Message("sdfkjabkf", "asdf"),
            Message("sdfkjabkf", "四道口附近啊看覅五俄方"),
            Message("sdfkjabkf", "四道口附近啊看覅都是浪费你为方便上的覅华为氟化锇反纳粹上的覅无法五俄方")
        ), resources = Resources.getSystem())
    }
}


@Composable
fun HelloScreen(){
    var name by remember { mutableStateOf("") }
    HelloContent(name = name, onValueChange = { name = it })
}
@Composable
fun HelloContent(name: String, onValueChange: (String) -> Unit) {
    val context = LocalContext.current
    Column(modifier = Modifier.padding(16.dp)) {
//        var name by remember { mutableStateOf("") }
        if (name.isNotEmpty()) {
            println("--->不空")
            Text(
                text = "Hello, $name!",
                modifier = Modifier.padding(bottom = 8.dp),
                style = MaterialTheme.typography.h5
            )
        }
        OutlinedTextField(//带边框的输入框
            value = name,
            onValueChange = onValueChange,
//            onValueChange = {
//                println("--->onValueChange")
//                name = it },
            label = {
                println("--->label")
                Text("Name Label") },
            textStyle = TextStyle(color = Color.Blue, fontWeight = FontWeight.Bold),
//            maxLines = 1,
            keyboardOptions = KeyboardOptions(
//                capitalization = KeyboardCapitalization.Words,
//                autoCorrect = false,
//                keyboardType = KeyboardType.Password,
                imeAction = ImeAction.Search
            ),
            keyboardActions = KeyboardActions(
                onGo = {Toast.makeText(context, "开始", Toast.LENGTH_SHORT).show()},
                onDone = {Toast.makeText(context, "确定", Toast.LENGTH_SHORT).show()},
                onNext = {Toast.makeText(context, "下一步", Toast.LENGTH_SHORT).show()},
                onPrevious = {Toast.makeText(context, "上一步", Toast.LENGTH_SHORT).show()},
                onSearch = {Toast.makeText(context, "搜索", Toast.LENGTH_SHORT).show()},
                onSend = { Toast.makeText(context, "发送", Toast.LENGTH_SHORT).show()}
            ),
            visualTransformation = PasswordVisualTransformation(),
        )
        TextField(//普通输入框，类似edittext
            modifier = Modifier.padding(top = 10.dp),
            value = name,
            onValueChange = onValueChange,
//            onValueChange = {
//                name = it
//                Log.e("TextFieldDemo", "输入内容更新：$it")
//            },
            label = { Text("Name Label") }
        )
    }
}

//保存状态的方式: Parcelable
@Parcelize
data class City(val name: String, val country: String) : Parcelable
@Composable
fun CityScreen() {
    var selectedCity = rememberSaveable {
        mutableStateOf(City("Madrid", "Spain"))
    }
}
//保存状态的方式: MapSaver
val CitySaver1/*: Saver<City, Any>*/ = run {
    val nameKey = "Name"
    val countryKey = "Country"
    mapSaver<City>(
        save = { mapOf(nameKey to it.name, countryKey to it.country) },
        restore = { City(it[nameKey] as String, it[countryKey] as String) }
    )
}
@Composable
fun CitySaver1(){
    var selectedCity = rememberSaveable(stateSaver = CitySaver1) {
        mutableStateOf(City("Madrid", "Spain"))
    }
}
//保存状态的方式: ListSaver
val CitySaver2/*: Saver<City, Any>*/= listSaver<City, Any>(
    save = { listOf(it.name, it.country) },
    restore = { City(it[0] as String, it[1] as String) }
)
@Composable
fun CitySaver2(){
    var city = rememberSaveable(stateSaver = CitySaver2) {
        mutableStateOf(City("Madrid", "Spain"))
    }
}